package model.dao;

import java.util.ArrayList;
import org.hibernate.Session;
import config.HibernateUtil;

public abstract class GenericDao<T> {

	private Session sessao;
	private Class<?> clazz;

	public GenericDao(Class<?> clazz) {
		this.clazz=clazz;
	}
	
	@SuppressWarnings("unchecked")
	public T convertInstanceOfObject(Object o) {
		try {
			return (T) clazz.cast(o);
		} catch (ClassCastException e) {
			return null;
		}
	}

	public boolean save(Object objeto) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.save(convertInstanceOfObject(objeto));
			sessao.getTransaction().commit();
			return true;
		} catch (Exception e) {
			sessao.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			sessao.close();
		}
	}

	public boolean delete(Object objeto) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.delete(convertInstanceOfObject(objeto));
			sessao.getTransaction().commit();
			return true;
		} catch (Exception e) {
			sessao.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			sessao.close();
		}
	}

	@SuppressWarnings("unchecked")
	public T find(Integer id) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			T objeto = (T) sessao.get(this.clazz, id);
			sessao.getTransaction().commit();
			return objeto;
		} catch (Exception e) {
			sessao.getTransaction().rollback();
			e.printStackTrace();
			return null;
		} finally {
			sessao.close();
		}
	}

	public boolean update(Object objeto) {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			sessao.update(convertInstanceOfObject(objeto));
			sessao.getTransaction().commit();
			return true;
		} catch (Exception e) {
			sessao.getTransaction().rollback();
			e.printStackTrace();
			return false;
		} finally {
			sessao.close();
		}
	}

	@SuppressWarnings("unchecked")
	public ArrayList<T> findAll() {
		try {
			sessao = HibernateUtil.getSessionFactory().openSession();
			sessao.beginTransaction();
			String sql = "from " + clazz.getSimpleName();
			ArrayList<T> list = (ArrayList<T>) sessao.createQuery(sql).list();
			sessao.getTransaction().commit();
			return list;
		} catch (Exception e) {
			sessao.getTransaction().rollback();
			e.printStackTrace();
			return null;
		} finally {
			sessao.close();
		}
	}

	public Session getSession() {
		if (this.sessao == null) {
			return sessao = HibernateUtil.getSessionFactory().openSession();
		}
		return this.sessao;
	}

}
